//
//  DirayDB.m
//  Four_years
//
//  Created by 中软国际088 on 15/11/13.
//  Copyright © 2015年 中软三班四年小组. All rights reserved.
//

#import "DirayDB.h"

#import "DirayDBUtill.h"
#import "DirayManagedObject.h"
@implementation DirayDB

- (id)init{

    if (self = [super init]) {
        DirayDBUtill *dbUitll = [[DirayDBUtill alloc]init];
        
        self.context = dbUitll.managedObjectContext;
    }

    return self;
}

- (NSMutableArray *)getAll{


    
    //创建请求数据对象
    NSFetchRequest *requst = [[NSFetchRequest alloc]initWithEntityName:@"Diray"];
    //根据请求对象进行查询
    NSArray *array = [_context executeFetchRequest:requst error:nil];
    
    NSMutableArray *reArray = [[NSMutableArray alloc]init];
    
    for (DirayManagedObject *di in array) {
        
        Diray *diray = [[Diray alloc]initWithTitle:di.title imageName:di.imageName date:di.date context:di.context classify:di.classify ifNumber:di.ifNumber];
        
        [reArray addObject:diray];
        
    }
    
    return reArray;

}
- (int)del:(Diray *)diray{

    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Diray"];
    
 //   NSPredicate *predicate = [NSPredicate predicateWithFormat:@""]
    NSArray *listData = [_context executeFetchRequest:request error:nil];
    
    if ([listData count]>0) {
        DirayManagedObject *di = [listData lastObject];
        
        [_context deleteObject:di];
        
        if ([_context hasChanges] && ![_context save:nil]) {
            NSLog(@"删除失败");
            return -1;
        }
        NSLog(@"删除成功");
    }
    

    return 0;
}
- (int)add:(Diray *)diray{
    
    DirayManagedObject *di = [NSEntityDescription insertNewObjectForEntityForName:@"Diray" inManagedObjectContext:_context];
    
    di.title = diray.title;
    di.imageName = diray.imageName;
    di.classify = diray.classify;
    di.ifNumber = diray.ifNumber;
    di.context = diray.context;
    di.date = diray.date;
    
    if ([_context hasChanges] && ![_context save:nil]) {
        
        NSLog(@"失败");
        return -1;
        
    }
else
    NSLog(@"成功");
    return 0;





}
@end
